<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/ukkepuk/source/php/classes/dao/AbstractDao.php'); 
require_once($_SERVER['DOCUMENT_ROOT'].'/ukkepuk/source/php/classes/model/extends/CalendarKids.php'); 
require_once($_SERVER['DOCUMENT_ROOT'].'/ukkepuk/source/php/classes/model/extends/CalendarDayparts.php'); 
require_once($_SERVER['DOCUMENT_ROOT'].'/ukkepuk/source/php/classes/model/Kid.php'); 
require_once($_SERVER['DOCUMENT_ROOT'].'/ukkepuk/source/php/classes/model/extends/KidWithTime.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/ukkepuk/source/php/classes/validation/ActionResult.php'); 
require_once($_SERVER['DOCUMENT_ROOT'].'/ukkepuk/source/php/classes/utils/CalendarUtils.php'); 


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of CalendarDaoreadCalendarKidsForDate
 *
 * @author virtual
 */
class CalendarDao extends AbstractDao{
    
    //return list of Calendar objects
    public function readCalendarByKidMonth($kid, $year, $month) {
        $firstDayOfMonth = mktime(0, 0, 0, $month, 1, $year);
        
        $queryCalendar = $this->mysqli->prepare("SELECT  date_format(c.DATE, '%Y%m%d'), c.START_TIME, c.END_TIME FROM calendar c WHERE c.KIDS_ID = ? and date_format(c.DATE, '%Y%m') = ?");
        $yearMonthNow =  date("Ym",$firstDayOfMonth);
        $kidId = $kid->getId();
        $queryCalendar->bind_param("is", $kidId, $yearMonthNow);
        $queryCalendar->execute();
		$queryCalendar->bind_result($date, $startTime, $endTime);
              
        //create initial array
        $result = $this->createEmptyCalendarDayparts($year, $month);
        
        while($queryCalendar->fetch()){
            $tmp = $result[$date];

             $daypart = new Daypart();
            
            $daypart->setStartTime($startTime);
            $daypart->setEndTime($endTime);
            
            $tmp->addDaypart($daypart);
            
        }
        
        $queryCalendar->close();
        return $result;
        
    }

    //return list of Calendar
    public function getNextCalendarDaysForKid($kid, $numDays){
        $getThisMonth = date("m");
        $getThisYear = date("Y");
        $getThisDay = date("d");
        $kidId = $kid->getId();
        $getStartDate =  $getThisYear . $getThisMonth . $getThisDay;
        $getEndDate = date('Ymd',mktime(0,0,0,$getThisMonth, $getThisDay+$numDays, $getThisYear));
        
        $queryCalendar = $this->mysqli->prepare("SELECT  date_format(c.DATE, '%Y%m%d'), c.START_TIME, c.END_TIME FROM calendar c WHERE c.KIDS_ID = ? and date_format(c.DATE, '%Y%m%d') > ? and date_format(c.DATE, '%Y%m%d') <= ?");
        $queryCalendar->bind_param("iss", $kidId, $getStartDate, $getEndDate);
        $queryCalendar->execute();
		$queryCalendar->bind_result($date, $startTime, $endTime);
        
        
        //create empty
        $result = array();
        for($i = 1; $i <= $numDays; $i++){
            $key = date("Ymd", mktime(0,0,0, $getThisMonth, $getThisDay + $i, $getThisYear));            
            $cal = new Calendar();
            $cal->setDate($key);
            $result[$key] = $cal;
        }

        //update dates from calendar
        while($queryCalendar->fetch()){
            $tmp = $result[$date];
            $tmp->setStartTime($startTime);
            $tmp->setEndTime($endTime);
            
        }
        $queryCalendar->close();
        return $result;
    }
    
    //UPDATE
    //create a result action object. this contains info about the result of the execution of this method
    
    public function createCalendar($calendar, $type) {
        
        
        //save diaper info for kid
        if($type == "override"){
            //Check if exists
                $this->removeCalendarTime($calendar);
                return $this->insertCalendarTime($calendar);
            
            
        }else if($type == "remove") {
            return $this->removeCalendarTime($calendar);
        }else if($type == "add"){
            return $this->insertCalendarTime($calendar);
        }
        
    }
    
    private function insertCalendarTime($calendar){
        $actionResult = new ActionResult();
        //set the executed action in the result
        $actionResult->savetype = "insertCalendarTime";

        $saveDate = CalendarUtils::getDbDateFromKey($calendar->getDate());
        $startTime = $calendar->getStartTime();
        $endTime = $calendar->getEndTime();
        $kidId = $calendar->getKidsId();
        
        //TODO: validate if insert is allowed:
        //- get max number of kids that can be in (global config)
        //- count number of kids that overlap in this interval on this day
        //- if equal or higher, reject
        
        $saveCalendarTime = $this->mysqli->prepare("INSERT INTO calendar(KIDS_ID, DATE, START_TIME, END_TIME) VALUES (?,?,?,?)");
        $saveCalendarTime->bind_param("isss", $kidId, $saveDate, $startTime, $endTime);
        if($saveCalendarTime->execute()){
            //if execute success, set succes to true
            $actionResult->success = true;
            //and add diaper in the result
            $actionResult->addActionParameter($calendar);
        }else {
            //if error during execution set reason of error in the result object
            $actionResult->error = $this->mysqli->error;
        }
        //close the statement
        $saveCalendarTime->close();

        //return the actionresult
        return $actionResult;
    }
    
    private function removeCalendarTime($calendar){
        $actionResult = new ActionResult();
        //set the executed action in the result
        $actionResult->savetype = "removeCalendarTime";

        $saveDate = CalendarUtils::getDbDateFromKey($calendar->getDate());
        $kidId = $calendar->getKidsId();
        
        $saveCalendarTime = $this->mysqli->prepare("DELETE FROM calendar WHERE KIDS_ID = ? AND DATE = ?");
        $saveCalendarTime->bind_param("is", $kidId, $saveDate);
        if($saveCalendarTime->execute()){
            //if execute success, set succes to true
            $actionResult->success = true;
            //and add diaper in the result
            $actionResult->addActionParameter($calendar);
        }else {
            //if error during execution set reason of error in the result object
            $actionResult->error = $this->mysqli->error;
        }
        //close the statement
        $saveCalendarTime->close();

        //return the actionresult
        return $actionResult;
    }
    
    private function updateCalendarTime($calendar) {
        $actionResult = new ActionResult();
        //set the executed action in the result
        $actionResult->savetype = "updateCalendarTime";

        $saveDate = CalendarUtils::getDbDateFromKey($calendar->getDate());
        $startTime = $calendar->getStartTime();
        $endTime = $calendar->getEndTime();
        $kidId = $calendar->getKidsId();
        
        $saveCalendarTime = $this->mysqli->prepare("UPDATE calendar SET START_TIME = ? , END_TIME = ?  WHERE KIDS_ID = ? AND  DATE = ?");
        
        $saveCalendarTime->bind_param("ssis", $startTime, $endTime, $kidId, $saveDate);
        if($saveCalendarTime->execute()){
            
            //if execute success, set succes to true
            $actionResult->success = true;
            //and add diaper in the result
            $actionResult->addActionParameter($calendar);
        }else {
            //if error during execution set reason of error in the result object
            $actionResult->error = $this->mysqli->error;
        }
        //close the statement
        $saveCalendarTime->close();

        //return the actionresult
        return $actionResult;
        
    }
    
    private function timeExists($calendar) {
        $saveDate = CalendarUtils::getDbDateFromKey($calendar->getDate());
        $startTime = $calendar->getStartTime();
        $endTime = $calendar->getEndTime();
        $kidId = $calendar->getKidsId();
        
        $exists = false;
        $calendarQuery = $this->mysqli->prepare("SELECT COUNT(*) FROM calendar WHERE KIDS_ID = ? AND DATE = ?");
        $calendarQuery->bind_param("is", $kidId, $saveDate);
        $calendarQuery->execute();
        $calendarQuery->bind_result($countResult);

        if($calendarQuery->fetch()){
            if($countResult > 0){
                
                $exists = true; 
            }
        }
        $calendarQuery->close();
        return $exists;
    }
    
    public function readCalendarKidsForDate($key) {
        $queryCalendar = $this->mysqli->prepare("select date_format(c.DATE, '%Y%m%d'), k.NAME, k.FIRST_NAME, c.START_TIME, c.END_TIME from kids k, calendar c where k.ID = c.KIDS_ID and date_format(c.DATE, '%Y%m%d') = ?");
        $queryCalendar->bind_param("s", $key);
        $queryCalendar->execute();
		$queryCalendar->bind_result($date, $kidName, $kidFirstName, $startTime, $endTime);
       
        $calendarKid = new CalendarKids();
        $calendarKid->setDate($key);
        
        
        
        $kids = array();
        
         while($queryCalendar->fetch()){
             $kid = new Kid();
             $kid->setName($kidName);
             $kid->setFirstname($kidFirstName);
             
             $calendar = new Calendar();
             $calendar->setStartTime($startTime);
             $calendar->setEndTime($endTime);
             
             $kid->addCalendar($calendar);
             
             array_push($kids, $kid);
             
        }
        
        $calendarKid->setKids($kids);
     
        
        return $calendarKid;
    }
    
    public function readCalendarKidsForWeek($year, $month, $day){
        $calendar = $this->createEmptyCalendarForWeek($year, $month, $day);
        
        $weekIndex = date("N", mktime(0, 0, 0, $month, $day, $year));
        
        $thisBeginWeek = date("Ymd", mktime(0,0,0, $month, $day-$weekIndex+1, $year));
        $thisEndWeek = date("Ymd",mktime(0,0,0, $month, $day+7-$weekIndex, $year));
        
    
        
        $queryCalendar = $this->mysqli->prepare("select date_format(c.DATE, '%Y%m%d'), k.NAME, k.FIRST_NAME, c.START_TIME, c.END_TIME from kids k, calendar c where k.ID = c.KIDS_ID and date_format(c.DATE, '%Y%m%d') >= ? and date_format(c.DATE, '%Y%m%d') <= ?");
        $queryCalendar->bind_param("ss", $thisBeginWeek, $thisEndWeek);
        $queryCalendar->execute();
		$queryCalendar->bind_result($dateKey, $kidName, $kidFirstName, $startTime, $endTime);

         
        //- loop over results: add kid found to day object 
        while($queryCalendar->fetch()){
            $calDay = $calendar[$dateKey];
            $tmpKid = new KidWithTime();
            $tmpKid->setName($kidName);
            $tmpKid->setFirstName($kidFirstName);
            $tmpKid->setStartTime($startTime);
            $tmpKid->setEndTime($endTime);
            $calDay->addKid($tmpKid);
        }   
        $queryCalendar->close();
        
        
        
        return $calendar;
        
    }
    
    public function readCalendarKidsForMonth($year, $month) {
        $calendar = $this->createEmptyCalendarForMonth($year, $month);
        $getThisMonth = date("m");
        $getThisYear = date("Y");
        $thisYearMonth = $getThisYear . $getThisMonth;
        $queryCalendar = $this->mysqli->prepare("select date_format(c.DATE, '%Y%m%d'), k.NAME, k.FIRST_NAME, c.START_TIME, c.END_TIME from kids k, calendar c where k.ID = c.KIDS_ID and date_format(c.DATE, '%Y%m') = ?");
        $queryCalendar->bind_param("s", $thisYearMonth);
        $queryCalendar->execute();
		$queryCalendar->bind_result($dateKey, $kidName, $kidFirstName, $startTime, $endTime);

         
        //- loop over results: add kid found to day object 
        while($queryCalendar->fetch()){
            $calDay = $calendar[$dateKey];
            $tmpKid = new Kid();
            $tmpKid->setName($kidName);
            $tmpKid->setFirstName($kidFirstName);
            $calDay->addKid($tmpKid);
        }
        
        $queryCalendar->close();
        return $calendar;

    }
    
    public function readCalendarForKid($kid, $year, $month){
        $firstDayOfMonth = mktime(0, 0, 0, $month, 1, $year);
        $yearMonthKey =  date("Ym",$firstDayOfMonth);
        
        $queryCalendar = $this->mysqli->prepare("SELECT  date_format(c.DATE, '%Y%m%d'), c.START_TIME, c.END_TIME FROM calendar c WHERE c.KIDS_ID = ? and date_format(c.DATE, '%Y%m') = ?");
        $kidId = $kid->getId();
        $queryCalendar->bind_param("is", $kidId, $yearMonthKey);
        $queryCalendar->execute();
		$queryCalendar->bind_result($date, $startTime, $endTime);
        $numDaysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
        
        $result = $this->createEmptyCalendarForMonth($year, $month);
        
        echo "xx";
       
        while($queryCalendar->fetch()){
            $tmp = $result[$date];
            
            
            
            $tmp->setStartTime($startTime);
            $tmp->setEndTime($endTime);
            
           
        }
        
        $queryCalendar->close();
        return $result;
    }

    private function createEmptyCalendarForWeek($year, $month, $day){
        $weekIndex = date("N", mktime(0, 0, 0, $month, $day, $year));
            
        $result = array();
    
        
         //create days of before today
        for($i = $weekIndex-1; $i >= 1; $i--){
            $key = date("Ymd", mktime(0,0,0, $month, $day-$i, $year));
            $cal = new CalendarKids();
            $cal->setDate($key);
            $cal->setItemType(constant('Calendar::PREVIOUS'));
            $result[$key] = $cal; 
        }
        
        for($i = 0; $i <= 7-$weekIndex; $i++){
            $key = date("Ymd",mktime(0,0,0, $month, $day+$i, $year));
            $cal = new CalendarKids();
            $cal->setDate($key);
            $cal->setItemType(constant('Calendar::CURRENT'));
            $result[$key] =  $cal;
        }
        
        return $result;
    }
    
    
    
    private function createEmptyCalendarForMonth($year, $month){
        $firstDayOfMonth = mktime(0, 0, 0, $month, 1, $year);
        $numDaysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
        
        $result = array();
        
        $weekIndex = date("N", mktime(0, 0, 0, $month, 1, $year));
        //create days of month before
        for($i = $weekIndex-1; $i >= 1; $i--){
            $key = date("Ymd", mktime(0,0,0, $month, 1 - $i, $year));
            $cal = new CalendarKids();
            $cal->setDate($key);
            $cal->setItemType(constant('Calendar::PREVIOUS'));
            $result[$key] = $cal; 
        }
        
        for($i = 1; $i <= $numDaysInMonth; $i++){
            $key = date("Ymd",mktime(0,0,0, $month, $i, $year));
            $cal = new CalendarKids();
            $cal->setDate($key);
            $cal->setItemType(constant('Calendar::CURRENT'));
            $result[$key] =  $cal;
        }
        
        $postWeek = 7 - ($numDaysInMonth + $weekIndex) % 7;
        
        if($postWeek != 0) {
            for($i = 0; $i <= $postWeek; $i++){
                                
                $key = date("Ymd", mktime(0,0,0, $month+1, 1 + $i, $year));
                
                $cal = new CalendarKids();
                $cal->setDate($key);
                $cal->setItemType(constant('Calendar::NEXT'));
                $result[$key] = $cal;
            }
        }
        
        return $result;
        
    }
    
    private function createEmptyCalendarDayparts($year, $month){
        $firstDayOfMonth = mktime(0, 0, 0, $month, 1, $year);
        $numDaysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
        
        $result = array();
        
        $weekIndex = date("N", mktime(0, 0, 0, $month, 1, $year));
        //create days of month before
        for($i = $weekIndex-1; $i >= 1; $i--){
            $key = date("Ymd", mktime(0,0,0, $month, 1 - $i, $year));
            $cal = new CalendarDayparts();
            $cal->setDate($key);
            $cal->setItemType(constant('Calendar::PREVIOUS'));
            $result[$key] = $cal; 
        }
        
        for($i = 1; $i <= $numDaysInMonth; $i++){
            $key = date("Ymd",mktime(0,0,0, $month, $i, $year));
            $cal = new CalendarDayparts();
            $cal->setDate($key);
            $cal->setItemType(constant('Calendar::CURRENT'));
            $result[$key] =  $cal;
        }
        
        $postWeek = 7 - ($numDaysInMonth + $weekIndex) % 7;
        
        if($postWeek != 0) {
            for($i = 0; $i <= $postWeek; $i++){
                                
                $key = date("Ymd", mktime(0,0,0, $month+1, 1 + $i, $year));
                
                $cal = new CalendarDayparts();
                $cal->setDate($key);
                $cal->setItemType(constant('Calendar::NEXT'));
                $result[$key] = $cal;
            }
        }
        
        return $result;
        
    }
}

?>
